package com.bicon.botu.mall.base.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.bicon.botu.mall.base.common.ValidationUtil;
import com.bicon.botu.mall.base.dto.DictionaryDTO;
import com.bicon.botu.mall.base.entity.Dictionary;
import com.bicon.botu.mall.base.entity.MallConfig;
import com.bicon.botu.mall.base.service.IDictionaryService;
import com.bicon.botu.mall.base.service.IMallConfigService;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.controller.BaseController;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.common.utils.BeanMapper;
import com.bicon.botu.core.base.common.utils.IdGen;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商城系统设置控制器
 * </p>
 *
 * @author tandk
 * @since 2017-07-31
 */
@RestController
@RequestMapping("/V3.0.0/system-config")
public class BaseConfigController extends BaseController {

    @Autowired
    IDictionaryService dictionaryService;

    @Autowired
    IMallConfigService mallConfigService;

    /**
     * 初始化所有字典缓存
     */
    @RequestMapping(value = "/initDictionaryRedis")
    public BaseResult initDictionaryRedis() {
        return dictionaryService.initDictionaryRedis() ? sendResult200() : sendResult500();
    }

    /**
     * 初始化基础字典缓存
     */
    @RequestMapping(value = "/initBaseDictionaryRedis")
    public BaseResult initBaseDictionaryRedis() {
        return dictionaryService.initBaseDictionaryRedis() ? sendResult200() : sendResult500();
    }

    /**
     * 新增字典
     *
     * @param name     字典名称
     * @param code     编码
     * @param parentId 父字典编号
     * @param type     类型
     * @param path     路径
     * @param level    等级
     * @param content  内容
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public BaseResult add(@RequestParam String name, @RequestParam String code, @RequestParam Integer parentId, @RequestParam Integer type,
                          @RequestParam String path, @RequestParam Integer level, @RequestParam String content,@RequestParam Integer order) {
        Dictionary dictionary = new Dictionary();
        dictionary.preInsert();
        dictionary.setDictionaryName(name);
        dictionary.setDictionaryCode(code);
        dictionary.setParentId(parentId);
        dictionary.setType(type);
        dictionary.setOrder(order);
        dictionary.setPath(path);
        dictionary.setLevel(level);
        dictionary.setContent(content);
        //检查是否重复
        int num = new Dictionary().selectCount(new EntityWrapper<Dictionary>().eq("parent_id", parentId).eq("dictionary_name", name).eq("dictionary_code", code).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if(num>0){
            return new BaseResult(Constants.RESPONSE_CODE_500,"该数据已经存在。");
        }
        if (dictionaryService.addDictionary(dictionary)) {
            return sendResult200(dictionary);
        } else {
            return sendResult500();
        }
    }

    /**
     * 修改字典
     *
     * @param id       字典Id
     * @param name     字典名称
     * @param code     编码
     * @param parentId 父字典编号
     * @param type     类型
     * @param path     路径
     * @param level    等级
     * @param content  内容
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult update(@RequestParam Integer id, @RequestParam String name, @RequestParam String code, @RequestParam Integer parentId, @RequestParam Integer type,
                             @RequestParam String path, @RequestParam Integer level, @RequestParam String content, @RequestParam Integer order) {

        Dictionary dictionary = new Dictionary();
        dictionary.preUpdate();
        dictionary.setId(id);
        dictionary.setDictionaryName(name);
        dictionary.setDictionaryCode(code);
        dictionary.setParentId(parentId);
        dictionary.setOrder(order);
        dictionary.setType(type);
        dictionary.setPath(path);
        dictionary.setLevel(level);
        dictionary.setContent(content);
        int num = new Dictionary().selectCount(new EntityWrapper<Dictionary>().notIn("id",id).eq("parent_id", parentId).eq("dictionary_name", name).eq("dictionary_code", code).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if(num>0){
            return new BaseResult(Constants.RESPONSE_CODE_500,"该数据已经存在。");
        }
        if (dictionaryService.updateDictionary(dictionary)) {
            return sendResult200(dictionary);
        }
        return sendResult500();
    }

    /**
     * 校验字典code是否存在
     *
     * @param code code
     */
    @RequestMapping(value = "/checkCodeIsExist")
    public BaseResult checkCodeIsExist(@RequestParam String code) {
        boolean b = true;
        int num = new Dictionary().selectCount(new EntityWrapper<Dictionary>().eq("dictionary_code", code).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if (num == 0) {
            b = false;
        }
        return sendResult200(b);
    }

    /**
     * 逻辑删除字典
     *
     * @param id 主键
     */
    @RequestMapping(value = "/del",method = RequestMethod.POST)
    public BaseResult del(@RequestParam int id) {
        if (dictionaryService.delDictionary(id)) {
            return sendResult200();
        }
        return sendResult500();
    }

    /**
     * 字典值排序
     * @param id
     * @param id1
     * @return
     */
    @RequestMapping(value = "/order",method = RequestMethod.POST)
    public BaseResult order(@RequestParam int id,@RequestParam int id1) {
        Dictionary dictionary = new Dictionary().selectById(id);
        Dictionary dictionary1 = new Dictionary().selectById(id1);
        int order = dictionary.getOrder();
        int order1 = dictionary1.getOrder();
        dictionary.setOrder(order1);
        dictionary.preUpdate();
        dictionary1.setOrder(order);
        dictionary1.preUpdate();
        if (dictionaryService.updateDictionary(dictionary)) {
            if (dictionaryService.updateDictionary(dictionary1)) {
                return sendResult200();
            }
        }
        return sendResult500();
    }


    /**
     * 查询字典详情
     *
     * @param id 字典id
     */
    @RequestMapping(value = "/findDictionaryById")
    public BaseResult findDictionaryById(@RequestParam int id) {
        Map<String, Object> map = new HashedMap();
        Dictionary dictionary = new Dictionary().selectById(id);
        map.put("dictionary", dictionary);
        return sendResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, map);
    }


    /**
     * 根据父字典id从db获取字典集合
     *
     * @param parentId 父字典id
     */
    @RequestMapping(value = "/findListByParentId")
    public BaseResult findListByParentId(@RequestParam Integer parentId) {
        return sendResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, new Dictionary().selectList(new EntityWrapper<Dictionary>().eq("parent_id", parentId).eq("logic_delete", Constants.DEL_LOGIC_NORMAL)));
    }

    /**
     * 获取所有根字典
     */
    @RequestMapping(value = "/findRootDictionary")
    public BaseResult findRootDictionary() {
        Dictionary dictionary = new Dictionary();
        EntityWrapper<Dictionary> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("parent_id", 0);
        entityWrapper.eq("logic_delete", Constants.DEL_LOGIC_NORMAL);
        return sendResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, dictionary.selectList(entityWrapper));
    }

    /**
     * 根据父code获取子字典
     */
    @RequestMapping(value = "/findChildDictionary")
    public BaseResult findChildDictionary(@RequestParam String code) {
        if(ValidationUtil.isEmpty(code)){
            return sendResult400("参数不完整");
        }
        Dictionary dictionary = new Dictionary().selectOne(new EntityWrapper<Dictionary>().eq("dictionary_code", code).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if(dictionary == null){
            return sendResult400();
        }
        EntityWrapper<Dictionary> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("parent_id", dictionary.getId());
        entityWrapper.eq("logic_delete", Constants.DEL_LOGIC_NORMAL);
        entityWrapper.orderBy("dictionary.order",true);
        List<Dictionary> list = dictionary.selectList(entityWrapper);
        List<DictionaryDTO> dtoList = BeanMapper.mapList(list, DictionaryDTO.class);
        return sendResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, dtoList);
    }

    /**
     * 根据字典id获取字典及子字典列表
     */
    @RequestMapping(value = "/findDictionaryListById")
    public BaseResult findDictionaryListByRootId(@RequestParam String id) {
        Dictionary dictionary = new Dictionary();
        EntityWrapper<Dictionary> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("logic_delete", Constants.DEL_LOGIC_NORMAL);
        entityWrapper.andNew("path like '" + id + ":%' or path=" + id);
        return sendResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, dictionary.selectList(entityWrapper));
    }

    /**
     * 新增保存配置
     * @param dictionaryCode
     * @param dictionaryValue NOT＿RECEIVED＿GOODS
     * @return
     */
    @RequestMapping(value = "/insert-config", method = RequestMethod.POST)
    public BaseResult insertConfig(@RequestParam String dictionaryCode,@RequestParam String dictionaryValue) {
        //检查code是否存在，若存在返回提示
        MallConfig mallConfig = new MallConfig().selectOne(new EntityWrapper<MallConfig>().eq("dictionary_code", dictionaryCode)
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if (mallConfig != null) {
            return new BaseResult(Constants.RESPONSE_CODE_601, Constants.RESPONSE_MESSAGE_601);
        }
        mallConfig = new MallConfig();
        mallConfig.preInsert();
        mallConfig.setTenantId(IdGen.uuid());
        mallConfig.setDictionaryCode(dictionaryCode);
        mallConfig.setDictionaryValue(dictionaryValue);
        if ( mallConfigService.insert(mallConfig)) {
                return sendResult200();
        }
        return sendResult500();
    }

    /**
     * 修改订单相关配置
     * @param dictionaryCode
     * @param dictionaryValue
     * @return
     */
    @RequestMapping(value = "/update-order-config", method = RequestMethod.POST)
    public BaseResult updateConfig(@RequestParam String dictionaryCode,@RequestParam String dictionaryValue) {
        //检查code是否存在，若存在返回提示
        MallConfig mallConfig = new MallConfig().selectOne(new EntityWrapper<MallConfig>().eq("dictionary_code", dictionaryCode)
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if (ValidationUtil.isEmpty(mallConfig)) {
            return new BaseResult(Constants.RESPONSE_CODE_602, Constants.RESPONSE_MESSAGE_602);
        }
        mallConfig.setDictionaryCode(dictionaryCode);
        mallConfig.setDictionaryValue(dictionaryValue);
        if ( mallConfigService.updateById(mallConfig)) {
            return sendResult200();
        }
        return sendResult500();
    }


    /**
     * 根据字典code获取配置的属性值
     * @param dictionaryCode 配置的字典值
     * @return
     */
    @RequestMapping(value = "/order-config-value", method = RequestMethod.GET)
    public BaseResult getOderConfigValue(@RequestParam String dictionaryCode) {
        //检查code是否存在，若存在返回提示
        MallConfig mallConfig = new MallConfig().selectOne(new EntityWrapper<MallConfig>().eq("dictionary_code", dictionaryCode)
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if (ValidationUtil.isEmpty(mallConfig)) {
            return new BaseResult(Constants.RESPONSE_CODE_602, Constants.RESPONSE_MESSAGE_602);
        }
        return sendResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, mallConfig);
    }


    /**
     * 根据code获取相关所有配置列表
     * @param code
     * @return
     */
    @RequestMapping(value = "/order-config-list", method = RequestMethod.GET)
    public BaseResult orderConfig(@RequestParam String code) {
        return sendResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, dictionaryService.getOrderConfig(code));
    }






}
